﻿using System;
using System.Collections.Generic;
using MarriageFertility.Missions;
using MarriageFertility.Texts;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.Encounters;
using TaleWorlds.CampaignSystem.GameMenus;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.CampaignSystem.Settlements.Locations;
using TaleWorlds.Localization;

namespace MarriageFertility.Behaviors;

public class DuelMenuBehavior : CampaignBehaviorBase
{
    public override void RegisterEvents()
    {
        CampaignEvents.OnSessionLaunchedEvent.AddNonSerializedListener(this, OnSessionLaunched);
    }

    private void OnSessionLaunched(CampaignGameStarter campaignGameStarter)
    {
        AddMenus(campaignGameStarter);
    }

    private void AddMenus(CampaignGameStarter campaignGameStarter)
    {
        campaignGameStarter.AddGameMenu(DuelManager.MdMenu, "{=!}{DUEL_MENU_TEXT}", InitMenu);
        campaignGameStarter.AddGameMenuOption(DuelManager.MdMenu, DuelManager.MdMenu + "_horse_duel",
            DuelText.HorseDuelText.ToString(), DuelStartCondition, StartDuelMissionWithHorse);
        campaignGameStarter.AddGameMenuOption(DuelManager.MdMenu, DuelManager.MdMenu + "_no_horse_duel",
            DuelText.NoHorseDuelText.ToString(), DuelStartCondition, StartDuelMissionNoHorse);
        campaignGameStarter.AddGameMenuOption(DuelManager.MdMenu, DuelManager.MdMenu + "leave",
            "{=2YYRyrOO}Leave...", DuelLeaveCondition, DuelLeave);
    }

    private void InitMenu(MenuCallbackArgs callbackArgs)
    {
        switch (DuelManager.DuelFightResult)
        {
            case DuelManager.DuelFightResultEnum.None:
                callbackArgs.MenuContext.SetBackgroundMeshName("wait_empire_town");
                MBTextManager.SetTextVariable("DUEL_MENU_TEXT", DuelManager.DuelMenuTitle);
                break;
            case DuelManager.DuelFightResultEnum.PlayerWon:
                MBTextManager.SetTextVariable("DUEL_MENU_TEXT", DuelWinText);
                DuelManager.CallBackEndEvent(true);
                break;
            case DuelManager.DuelFightResultEnum.PlayerLost:
                MBTextManager.SetTextVariable("DUEL_MENU_TEXT", DuelLostText);
                DuelManager.CallBackEndEvent(false);
                break;
        }
    }

    private bool DuelStartCondition(MenuCallbackArgs args)
    {
        args.optionLeaveType = GameMenuOption.LeaveType.Mission;
        return DuelManager.DuelFightResult == DuelManager.DuelFightResultEnum.None &&
               (DuelManager.DuelHero != null || DuelManager.DuelEnemies.Count > 0);
    }

    public override void SyncData(IDataStore dataStore)
    {
        
    }

    private void StartDuelMissionWithHorse(MenuCallbackArgs args)
    {
        StartDuelMission(true);
    }

    private void StartDuelMissionNoHorse(MenuCallbackArgs args)
    {
        StartDuelMission(false);
    }

    public void StartDuelMission(bool withHorse)
    {
        string scene;
        string sceneLevel = "";
        int wallLevel = 1;
        bool isInsideSettlement;

        List<string> stringList = new List<string>()
        {
            "battle_terrain_biome_030",
            "battle_terrain_biome_053",
            "battle_terrain_biome_088"
        };
        if (DuelManager.DuelHero == null)
            DuelManager.DuelHero = Campaign.Current.ConversationManager.OneToOneConversationCharacter;


        if (PlayerEncounter.Current != null && PlayerEncounter.InsideSettlement && Settlement.CurrentSettlement.IsTown)
        {
            Settlement currentSettlement = Settlement.CurrentSettlement;
            if (currentSettlement.IsTown || currentSettlement.IsCastle)
                wallLevel = currentSettlement.Town.GetWallLevel();
            scene = GetLocation(currentSettlement).GetSceneName(wallLevel);
            isInsideSettlement = true;
        }
        else
        {
            scene = PlayerEncounter.GetBattleSceneForMapPatch(
                Campaign.Current.MapSceneWrapper.GetMapPatchAtPosition(MobileParty.MainParty.Position2D));
            isInsideSettlement = false;
        }

        if (stringList.Contains(scene))
            scene = "battle_terrain_biome_065";

        switch (DuelManager.DuelFightType)
        {
            case DuelManager.DuelFightTypeEnum.Single:
                DuelMissions.OpenDuelMission(scene, sceneLevel, withHorse, true, isInsideSettlement);
                break;
            case DuelManager.DuelFightTypeEnum.Multiple:
                DuelMissions.OpenMultipleMission(scene, sceneLevel, withHorse, true, isInsideSettlement);
                break;
            default:
                DuelMissions.OpenDuelMission(scene, sceneLevel, withHorse, true, isInsideSettlement);
                break;
        }
    }

    private Location GetLocation(Settlement settlement)
    {
        List<string> list = new List<string> { "arena", "lordshall" };
        foreach (var id in list)
        {
            var location = settlement.LocationComplex.GetLocationWithId(id);
            if (location != null) return location;
        }

        return null;
    }

    private bool DuelLeaveCondition(MenuCallbackArgs args)
    {
        args.optionLeaveType = GameMenuOption.LeaveType.Leave;
        return true;
    }

    private void DuelLeave(MenuCallbackArgs args)
    {
        try
        {
            PlayerEncounter.Finish();
        }
        catch (Exception)
        {
        }
    }

    private TextObject DuelTextObject
    {
        get
        {
            TextObject duelTextObject = DuelText.DuelRequestText;
            duelTextObject.SetTextVariable("heroName", DuelManager.DuelHero.Name);
            return duelTextObject;
        }
    }

    private TextObject DuelWinText
    {
        get
        {
            TextObject duelTextObject = DuelText.DuelWinText;
            return duelTextObject;
        }
    }

    private TextObject DuelLostText
    {
        get
        {
            TextObject duelTextObject = DuelText.DuelLoseText;
            return duelTextObject;
        }
    }
}